package com.baomidou.test;

import com.baomidou.mybatisplus.MybatisSessionFactoryBuilder;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.toolkit.TableInfoHelper;
import com.baomidou.test.entity.User;
import java.io.InputStream;
import java.util.List;
import java.util.UUID;
import org.apache.ibatis.session.SqlSessionFactory;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @ FileName: ApplicationMybatisPlus.java
 * @ Author: WeiHui-Z
 * @ Date: 2016-12-12  12:59
 * @ Version: v1.0.0
 */
public class ApplicationMybatisPlus {

	private static final Logger LOGGER = LoggerFactory.getLogger(ApplicationMybatisPlus.class);

	@Before
	public void setUp() {
		// 加载配置文件
		InputStream in = ApplicationMybatisPlus.class.getClassLoader().getResourceAsStream("mybatis-config.xml");
		MybatisSessionFactoryBuilder mf = new MybatisSessionFactoryBuilder();
		SqlSessionFactory sqlSessionFactory = mf.build(in);
		TableInfoHelper.initSqlSessionFactory(sqlSessionFactory);
		sqlSessionFactory.openSession(false);
	}

	/**
	 * 保存一条记录
	 */
	@Test
	public void testInsertOne() {
		User t1 = new User();
		t1.setName("小珊珊");
		t1.setPassword("123456");
		t1.setSalt(UUID.randomUUID().toString().replaceAll("-", ""));
		t1.setRole("Admin");
		LOGGER.info("result ：{}", t1.insert());
	}

	@Test
	public void testFindOne() {
		User user = new User();
		user.setId(17L);

		User user1 = user.selectById();
		LOGGER.info("result：{}", user1);

		User user2 = user.selectById(17L);
		LOGGER.info("result：{}", user2);
	}

	@Test
	public void testFindOneWhereCause() {
		User user = new User();
		User selectOne = user.selectOne("id={0}", 17L);
		LOGGER.info("result：{}", selectOne);
	}

	@Test
	public void testFindAll() {
		User user = new User();
		List<User> users = user.selectAll();
		LOGGER.info("result：{}", users);
	}

	@Test
	public void testFindPage() {
		User user = new User();
		Page<User> page = new Page<>();
		Page<User> userPage = user.selectPage(page, null);
		LOGGER.info("result：{}", userPage);
		LOGGER.info("result：{}", userPage.getRecords());

		user.setName("小珊珊");
		EntityWrapper<User> wrapper = new EntityWrapper<>(user);
		Page<User> userPage1 = user.selectPage(page, wrapper);
		LOGGER.info("result：{}", userPage1);
		LOGGER.info("result：{}", userPage1.getRecords());
	}

	@Test
	public void testCount() {
		User user = new User();
		int count = user.selectCount(null);
		LOGGER.info("result：{}", count);

		user.setName("小珊珊");
		int count2 = user.selectCount(new EntityWrapper<>(user));
		LOGGER.info("result：{}", count2);
	}

	@Test
	public void testUpdate() {
		User user = new User();
		user.setName("小毛怪");

		user.update("id={0}", 17);

		User user2 = user.selectById(17L);
		LOGGER.info("result：{}", user2);
	}

}